import { login } from '@/api/user'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'

export const state = {
  token: getToken(),
  userInfo: getUserInfo()
}

export const getters = {
}

export const mutations = {
  // 登录保存token
  setToken(state, token) {
    state.token = token
  },

  // 用户信息数据
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}

export const actions = {
  // 登录
  async login(content, data) {
    const res = await login(data)
    // console.log(res)
    content.commit('setToken', res.data.token.token)
    content.commit('setUserInfo', res.data.user)
    setToken(res.data.token.token)
    setUserInfo(res.data.user)
  },
  // 退出登录
  // 退出登录
  logout(content) {
    // 清除vuex中的token
    content.commit('setToken', '')
    // 清除本地存储中的token及userInfo
    removeToken()
    removeUserInfo()
    // 清除用户信息
    content.commit('setUserInfo', {})
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
